package com.zxl.yjb.http.api;


import com.zxl.yjb.app.MyApplication;
import com.zxl.yjb.bean.HttpResult;
import com.zxl.yjb.http.GsonConvert.ResponseConverterFactory;
import com.zxl.yjb.http.HostUrl;
import com.zxl.yjb.http.cookiejar.ClearableCookieJar;
import com.zxl.yjb.http.cookiejar.PersistentCookieJar;
import com.zxl.yjb.http.cookiejar.cache.SetCookieCache;
import com.zxl.yjb.http.cookiejar.persistence.SharedPrefsCookiePersistor;
import com.zxl.yjb.http.customexception.ApiException;
import com.zxl.yjb.utils.LogUtil;

import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2017/6/17.
 */

public class RetrofitHelper {

    public static final String TAG=RetrofitHelper.class.getSimpleName();
//    public static final String BASE_URL = "http://47.93.33.168:9999/";
    public static final String BASE_URL = HostUrl.BASE_URL;

    private static final int DEFAULT_TIMEOUT = 20;
    private ApiManager apiManager;
    private Retrofit retrofit;

    /**
     * 创建私有构造函数  只能在本类中进行初始化
     */
    private RetrofitHelper() {

        ClearableCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(MyApplication.getContext()));

        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor (new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                //打印retrofit日志
                LogUtil.e("RetrofitLog",message);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);


        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .cookieJar(cookieJar);
        OkHttpClient client = builder
                //设置缓存
                //.cache(new Cache(httpCacheDirectory, 10 * 1024 * 1024))
                //log请求参数
                .addInterceptor(loggingInterceptor)
                .build();
        //实例化 retrofit对象
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
//                .client(builder.build())
                .client(client)
//                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(ResponseConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        apiManager=retrofit.create(ApiManager.class);
    }

    /**
     * 创建HttpMethod实例
     */
    public static class SingleInstance {
        private static final RetrofitHelper INSTANCE = new RetrofitHelper();
    }

    /**
     * 获得HttpMethod实例
     *
     * @return
     */
    public static RetrofitHelper getInstance() {
        return SingleInstance.INSTANCE;
    }


    /**
     * 获取ApiManger实例
     * @return
     */
    public ApiManager getApiManager(){
        return apiManager;
    }

    /**
     * 用来统一处理Http的ResultCode,并将HttpResult的data部分剥离出来返还给observer
     *
     * @param <T> Observer 真正用的的数据就是HttpResult中的data
     */
    public static class HttpResultFuct<T> implements Function<HttpResult<T>, T> {
        @Override
        public T apply(@NonNull HttpResult<T> tHttpResult) throws Exception {
            int status = tHttpResult.getState();
            if (tHttpResult.getState() !=0000)    //请求失败
                throw new ApiException(tHttpResult.getMessage(),tHttpResult.getState()); //抛出自定义异常
            return tHttpResult.getData();
        }
    }
}
